<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 社区
 *
 * @author      Eden
 * @datetime    2016/12/10 23:51
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Index_Model extends ADM_Model
{

    private $total = 0;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('timer');
    }

    public function getLists($type, $offset = 0, $limit = 20)
    {
        $result = $this->_getBbsLists(null, $type, $offset, $limit);
        $ret = array(
            'total' => 0,
            'data' => [],
            'nextPage' => false
        );
        if ($result) {
            $ret = array(
                'total' => intval($this->total),
                'data' => $result,
                'nextPage' => $this->total > ($offset + $limit)
            );
        }
        return $ret;
    }

    /**
     * 获取指定用户的发帖
     * @param $userid
     * @param $type
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function getListsByUserId($userid, $type, $offset = 0, $limit = 20)
    {
        $result = $this->_getBbsLists($userid, $type, $offset, $limit);
        $ret = array(
            'total' => 0,
            'data' => [],
            'nextPage' => false
        );
        if ($result) {
            $ret = array(
                'total' => intval($this->total),
                'data' => $result,
                'nextPage' => $this->total > ($offset + $limit)
            );
        }
        return $ret;
    }

    /**
     * 获取 BBS 列表
     * @param int $offset
     * @param int $pageSize
     * @return bool
     */
    protected function _getBbsLists($userId = null, $type = '', $offset = 0, $pageSize = 20)
    {
        $db = clone($this->db);
        $where = array('b.status' => 1);
        if (!empty($userId)) {
            $where['b.userId'] = $userId;
        }

        if ($type == 'text') {
            $db->where_in('ba.attachment', array(''));
        } else if ($type == 'mixed') {
            $db->where_not_in('ba.attachment', array(''));
        }
        $db->join('bbs_attachment as ba', 'ba.bbsId = b.id');
        $db->where($where);
        $this->total = $db->count_all_results('bbs as b');

        if (empty($this->total)) {
            return false;
        }

        $bbsDb = clone($this->db);
        $bbsDb->where($where)
            ->select('b.id, b.userId, b.content, b.likes, b.comments, b.source, b.created, ba.attachment')
            ->from('bbs as b')
            ->limit($pageSize, $offset)
            ->join('bbs_attachment as ba', 'ba.bbsId = b.id')
            ->order_by('b.created', 'DESC');
        if ($type == 'text') {
            $bbsDb->where_in('ba.attachment', array(''));
        } else if ($type == 'mixed') {
            $bbsDb->where_not_in('ba.attachment', array(''));
        }
        $query = $bbsDb->get();

        $bbsRows = $query->result_array();
        if (empty($bbsRows)) {
            return false;
        }

        $userIds = array();
        if (is_array($bbsRows)) foreach ($bbsRows as &$row) {
            $userId = $row['userId'];
            array_push($userIds, $userId);
            $row['bbsId'] = intval($row['id']);
            $row['userId'] = intval($userId);
            $row['likes'] = intval($row['likes']);
            $row['comments'] = intval($row['comments']);
            $row['created'] = formateTimeStamp($row['created']);
            $row['attachment'] = bbsThumb($row['attachment'], '', 360, 237);
        }

        $userInfos = $this->_getUsersInfo($userIds);
        $config = $this->getBbsConfig();
        foreach ($bbsRows as &$bbs) {
            $bbsUserId = $bbs['userId'];
            if ($bbs['source'] == 'admin' && !empty($config)) {
                $user = [
                    'avatar' => thumb($config['thumb'], 100, 100),
                    'nickName' => $config['nickname']
                ];
            } else {
                $user = !empty($userInfos[$bbsUserId]) ? $userInfos[$bbsUserId] : ['avatar' => '', 'nickName' => ''];
            }

            $bbs = array_merge($bbs, $user);
        }
        return $bbsRows;
    }

    /**
     * 获取设置
     * @return mixed
     */
    protected function getBbsConfig()
    {
        $this->load->model('common/Setting_Model', 'sets');
        return $this->sets->getSetting('system', 'bbs');
    }

    /**
     * 获取用户数据
     * @param array $userIds
     * @return array
     */
    protected function _getUsersInfo($userIds = array())
    {
        $query = $this->db->select('u.id, u.nickName, up.avatar')
            ->from('user as u')
            ->join('user_profile as up', 'up.userId = u.id')
            ->where_in('u.id', $userIds)
            ->get();
        $rows = $query->result_array();
        $users = array();
        if ($rows && is_array($rows)) foreach ($rows as $row) {
            $userId = $row['id'];
            $info = array();
            $info['avatar'] = thumb($row['avatar'], 100, 100);
            $info['nickName'] = $row['nickName'];
            $users[$userId] = $info;
        }
        return $users;
    }

    /**
     * 删除贴,不作处理删除
     * @param $bbsId
     * @return bool
     */
    public function remove($bbsId)
    {
        $bdb = clone($this->db);
        $q = $bdb->get_where('bbs', array('id' => $bbsId));
        if ($q->row_array()) {
            $this->db->where(array('id' => $bbsId));
            return $this->db->update('bbs', array('status' => -1));
        } else {
            $this->setError('该帖子不存在');
            return false;
        }

    }

    public function getBbsDetail($bbsId)
    {
        $bbsDb = clone($this->db);
        $query = $bbsDb->where(array('b.status' => 1, 'b.id' => $bbsId))
            ->select('b.id, b.userId, b.content, b.likes, b.comments, b.source, b.created, ba.attachment')
            ->from('bbs as b')
            ->join('bbs_attachment as ba', 'ba.bbsId = b.id')
            ->order_by('b.created', 'DESC')
            ->get();

        $bbsRows = $query->row_array();
        if (empty($bbsRows)) {
            return false;
        }
        $userId = $bbsRows['userId'];

        $row['bbsId'] = intval($bbsRows['id']);
        $row['userId'] = intval($userId);
        $row['content'] = value($bbsRows, 'content');
        $row['likes'] = intval($bbsRows['likes']);
        $row['comments'] = intval($bbsRows['comments']);
        $row['created'] = formateTimeStamp($bbsRows['created']);
        $row['attachment'] = bbsThumb($bbsRows['attachment'], '', 360, 237);
        $row['nickName'] = '';
        $row['avatar'] = '';

        if ($bbsRows['source'] == 'admin') {
            $bbsConfig = $this->getBbsConfig();
            $avatar = $nickName = '';
            if ($bbsConfig) {
                $avatar = thumb($bbsConfig['thumb'], 100, 100);
                $nickName = $bbsConfig['nickname'];
            }
            $userInfo = [
                'avatar' => $avatar,
                'nickName' => $nickName
            ];
        } else {
            $userInfo = $this->_getUserInfo($userId);
        }

        if ($userInfo) {
            $row = array_merge($row, $userInfo);
        }

        return $row;
    }

    /**
     * 获取用户数据
     * @param int $userId
     * @return array
     */
    protected function _getUserInfo($userId)
    {
        $query = $this->db->select('u.id, u.nickName, up.avatar')
            ->from('user as u')
            ->join('user_profile as up', 'up.userId = u.id')
            ->where(array('u.id' => $userId))
            ->get();
        $row = $query->row_array();
        $info = array();
        if ($row) {
            $info['avatar'] = thumb($row['avatar'], 100, 100);
            $info['nickName'] = $row['nickName'];
        }
        return $info;
    }

    /**
     * 获取列表
     * @param $bbsId
     * @param $offset
     * @param $limit
     * @return array|bool
     */
    public function getCommentsLists($bbsId, $offset, $limit)
    {
        $tdb = clone($this->db);
        $where = array(
            'status' => 1,
            'bbsId' => $bbsId
        );
        $tdb->where($where);
        $this->total = $tdb->count_all_results('bbs_comments');
        if (empty($this->total)) {
            return false;
        }

        $cdb = clone($this->db);
        $query = $cdb->select('id, userId, text, created')
            ->from('bbs_comments')
            ->where($where)
            ->limit($limit, $offset)
            ->order_by('created', 'DESC')
            ->get();
        $lists = $query->result_array();
        if (empty($lists)) {
            $this->total = 0;
            return false;
        }

        $userIds = array();
        $ids = array();
        if (is_array($lists)) foreach($lists as $list) {
            $id = $list['id'];
            $userId = $list['userId'];
            array_push($ids, $id);
            array_push($userIds, $userId);
        }

        $replys = $this->getReply($ids);

        if (!empty($replys)) foreach ($replys as $reply) {
            $userId = $reply['userId'];
            array_push($userIds, $userId);
        }
        $userInfo = $this->_getUsersInfo($userIds);

        $replyInfo = array();
        foreach($replys as $reply) {
            $userId = $reply['userId'];
            $commentId = $reply['commentId'];
            $repData = array();
            $repData['replyId'] = intval($reply['id']);
            $repData['content'] = $reply['content'];
            $repData['created'] = formateTimeStamp($reply['created']);
            $repData['nickName'] = value($userInfo, array($userId, 'nickName'), '');
            $repData['avatar'] = value($userInfo, array($userId, 'avatar'), '');
            $replyInfo[$commentId] = $repData;
        }

        $returns = array();
        foreach ($lists as $list) {
            $cId = $list['id'];
            $uId = $list['userId'];
            $nickName = value($userInfo, array($uId, 'nickName'), '');
            $avatar = value($userInfo, array($uId, 'avatar'), '');
            $returns[] = array(
                'commentId' => intval($cId),
                'nickName' => !empty($nickName) ? $nickName : '',
                'avatar' => !empty($avatar) ? $avatar : '',
                'text' => $list['text'],
                'created' => formateTimeStamp($list['created']),
                'reply' => !empty($replyInfo[$cId]) ? $replyInfo[$cId] : []
            );
        }

        return $returns;
    }

    /**
     * 删除评论
     * @param $commentId
     * @return mixed
     */
    public function deleteComment($commentId)
    {
        $cDb = clone($this->db);
        $q = $cDb->get_where('bbs_comments', array('id' => $commentId));
        $r = $q->row_array();
        if (!$r) {
            $this->setError('评论不存在');
            return false;
        }

        $db = clone($this->db);
        $q = $db->get_where('bbs', array('id' => $commentId));
        $r = $q->row_array();
        if (!$r) {
            $this->setError('评论不存在');
            return false;
        }

        $coms = intval($r['comments']) - 1;
        $db->where(array('id' => $commentId));
        $db->update('bbs', array('comments' => $coms));

        $this->db->where('id', $commentId);
        return $this->db->update('bbs_comments', array('status' => -1));
    }

    /**
     * 所有回复
     * @param $ids
     * @return mixed
     */
    private function getReply($ids)
    {
        $replyDb = clone($this->db);
        $query = $replyDb->select('id, commentId, userId, content, created')
            ->where_in('commentId', $ids)
            ->where(array('status' => 1))
            ->from('bbs_comments_reply')
            ->get();
        $result = $query->result_array();
        return $result;
    }

    /**
     * 删除回复
     * @param $replyId
     * @return bool
     */
    public function deleteReply($replyId)
    {
        $cDb = clone($this->db);
        $q = $cDb->get_where('bbs_comments_reply', array('id' => $replyId));
        $r = $q->row_array();
        if (!$r) {
            $this->setError('回复不存在');
            return false;
        }
        $this->db->where('id', $replyId);
        return $this->db->update('bbs_comments_reply', array('status' => -1));
    }

    /**
     * @return int
     */
    public function getTotal()
    {
        return $this->total;
    }

    /**
     * 发布主题
     * @param $data
     * @return bool
     */
    public function publish($data)
    {
        $db = clone($this->db);
        $db->insert('bbs', [
            'userId' => 0,
            'content' => value($data, 'content', ''),
            'likes' => intval($data['likes']),
            'comments' => 0,
            'created' => dateTime(),
            'status' => 1,
            'source' => 'admin'
        ]);

        $bbsId = $db->insert_id();
        if (!empty($bbsId)) {
            unset($db);
            $db = clone($this->db);
            $db->insert('bbs_attachment', [
                'bbsId' => $bbsId,
                'attachment' => !empty($data['attachment']) ? json_encode($data['attachment']) : ''
            ]);
            return $bbsId;
        }
        return false;
    }
}
